package com.yuanduan.mplus.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.ViewTarget;
import com.cj.framework.app.BaseActivity;
import com.cj.framework.app.BaseApplication;
import com.cj.framework.util.FileUtils;
import com.cj.framework.util.IOkHttp;
import com.cj.framework.util.OkHttpImp;
import com.cj.framework.widget.CircleImageView;
import com.cj.framework.widget.CircleView;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;
import com.yuanduan.mplus.db.dao.UserDao;
import com.yuanduan.mplus.db.entity.User;
import com.yuanduan.mplus.presenter.Main_DataManager;

import java.io.File;
import java.util.List;

/**
 * 首页
 */
public class Main1Activity extends BaseActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener {
    private NavigationView nv;
    private DrawerLayout dlayout;
    private ImageView iv_bar_person;
    private ImageView iv_bar_message;
    private LinearLayout ll_breaksearch;
    private LinearLayout ll_drivescore;
    private LinearLayout ll_ordersearch;
    private LinearLayout ll_4;
    private RelativeLayout rl_head;
    private CircleImageView circleImageView;
    private TextView tv_userInfo;
    private IOkHttp okHttp;

    private User user;
    private Main_DataManager dataManager;

    private BroadcastReceiver headReceiver;
    private BroadcastReceiver nameReceiver;


    @Override
    protected void findId() {
        nv = (NavigationView) findViewById(R.id.main_nv);
        rl_head= (RelativeLayout) nv.getHeaderView(0);
        tv_userInfo= (TextView) rl_head.findViewById(R.id.main_tv_message);
        circleImageView= (CircleImageView) rl_head.findViewById(R.id.main_circleImage);
        dlayout = (DrawerLayout) findViewById(R.id.main_dlayout);
        iv_bar_person = (ImageView) findViewById(R.id.main_bar_iv_person);
        iv_bar_message = (ImageView) findViewById(R.id.main_bar_iv_message);
        ll_4= (LinearLayout) findViewById(R.id.main_ll_4);
        ll_breaksearch= (LinearLayout) findViewById(R.id.main_ll_breaksearch);
        ll_drivescore= (LinearLayout) findViewById(R.id.main_ll_drivescore);
        ll_ordersearch= (LinearLayout) findViewById(R.id.main_ll_ordersearch);
    }

    @Override
    protected void logic() {
        okHttp=new OkHttpImp();
        //获取用户信息
        UserDao userDao = BaseApplication.getDaoSession().getUserDao();
        List list = userDao.queryBuilder().list();
        if (list.size() == 0) {
            this.finish();
        }
        user = (User) list.get(0);


        //设置nv的头部信息(人员信息和头像）
        Glide.with(this)
                .load(Config.URL+user.getUserHead()+"?"+System.currentTimeMillis())
                .asBitmap()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        if(resource!=null){
                            circleImageView.setBitmap(resource);
                            saveBitmap(resource);
                        }
                    }
                });

        //注册广播用于更新头像
        IntentFilter filter=new IntentFilter(PersonalSetting.TYPE_HEAD);
        registerReceiver(headReceiver=new HeadRegister(),filter);

        //注册广播用于更新名字
        IntentFilter filter1=new IntentFilter(PersonalSetting.TYPE_NAME);
        registerReceiver(nameReceiver=new NameRegister(),filter1);

        if(user.getUserType().equals("1")){
            tv_userInfo.setText(user.getRealName()+"\n"+user.getCarTeamName());
        }else if(user.getUserType().equals("2")){
            tv_userInfo.setText("车队管理员");
        }else{
            tv_userInfo.setText("游客");
        }

        //设置入口
        iv_bar_person.setOnClickListener(this);
        iv_bar_message.setOnClickListener(this);
        ll_breaksearch.setOnClickListener(this);
        ll_drivescore.setOnClickListener(this);
        ll_ordersearch.setOnClickListener(this);
        ll_4.setOnClickListener(this);
        nv.setNavigationItemSelectedListener(this);
        rl_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!user.getUserType().equals("3")){
                    openActivity(PersonalSetting.class);
                }else{
                    Toast.makeText(Main1Activity.this,"游客无法更改个人设置，请注册登录！",Toast.LENGTH_SHORT).show();
                }
            }
        });

        //设置侧滑栏的菜单
        setMenu();

        //设置显示导航还是车队信息
        setL4();

        //设置数据管理器
        dataManager=new Main_DataManager(this);

    }

    private void saveBitmap(final Bitmap bitmap) {
        new Thread(){
            @Override
            public void run() {
                if(bitmap==null){
                    return;
                }
                FileUtils.saveBitmap(Config.HEADLOCATION,bitmap);
            }
        }.start();
    }

    //设置侧滑栏的菜单
    private void setMenu() {
        if(user.getUserType().equals("1")){
            nv.inflateMenu(R.menu.menu_main_nv);
        }else if(user.getUserType().equals("2")){
            nv.inflateMenu(R.menu.menu_main_nv_manager);
        }else{
            nv.inflateMenu(R.menu.menu_main_nv);
        }
    }


    @Override
    protected int setLayout() {
        return R.layout.activity_main1;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_bar_iv_person:  //toolbar弹出导航栏
                dlayout.openDrawer(Gravity.LEFT);
                break;
            case R.id.main_bar_iv_message:  //消息入口
//                openActivity(MessageActivity.class);
                break;
            case R.id.main_ll_breaksearch:  //违章记录

                break;
            case R.id.main_ll_drivescore:  //行车记录

                break;
            case R.id.main_ll_ordersearch:  //运单查询

                break;
            case R.id.main_ll_4:  //导航或者车队信息

                break;

        }
    }

    //退出程序
    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setMessage("确认退出程序");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent=new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        builder.create().show();
    }

    //设置导航还是车队信息
    private TextView tv_4;
    private ImageView iv_4;
    private void setL4(){
        tv_4= (TextView) findViewById(R.id.main_ll_tv_4);
        iv_4= (ImageView) findViewById(R.id.main_ll_iv_4);
        if(user.getUserType().equals("1")){
            tv_4.setText("导航");
            iv_4.setImageResource(R.mipmap.main_navigation);
        }else if(user.getUserType().equals("2")){
            tv_4.setText("车队信息");
            iv_4.setImageResource(R.mipmap.main_carinfo);
        }else{
            tv_4.setText("导航");
            iv_4.setImageResource(R.mipmap.main_navigation);
        }
    }

    //导航栏内容设置；
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case R.id.main_nv_consult: //资讯
                openActivity(Consult1Activity.class);
                break;
            case R.id.main_nv_tongzhi: //通知
                openActivity(NotifyActivity.class);
                break;
            case R.id.main_nv_topic:  //论坛
                openActivity(TopicActivity.class);
                break;
            case R.id.main_nv_store:  //商城
                openActivity(StoreActivity.class);
                break;
            case R.id.main_nv_drivescore:  //驾驶评分
                openActivity(DriverScore1Activity.class);
                break;
            case R.id.main_nv_driveanalyse:  //车队驾驶分析
                openActivity(DriveAnalyseActivity.class);
                break;
            case R.id.main_nv_driverecord:  //行车记录
//                openActivity();
                break;
            case R.id.main_nv_zxing:  //分享二维码
                openActivity(ZxingActivity.class);
                break;
            case R.id.main_nv_comments:  //点评
//                openActivity(CommentsReceivedActivity.class);
                break;
            case R.id.main_nv_setting:  //设置是否退出
                openActivity(Setting1Activity.class);
                break;
        }
        return true;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(headReceiver);
        unregisterReceiver(nameReceiver);
    }

    class HeadRegister extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            circleImageView.setBitmap(FileUtils.getBitmapFromFile(Config.HEADLOCATION));
        }
    }

    class NameRegister extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String name=intent.getStringExtra("name");
            tv_userInfo.setText(name+"\n"+user.getCarTeamName());
        }
    }
}
